<template>
  <PageWrapper contentClass="flex" contentFullHeight dense fixedHeight>
    <a-card>
      <div style="margin-bottom: 20px">
        <a-form :model="formState">
          <a-row :gutter="[20, 20]">
            <a-col :xs="24" :sm="6">
              <a-form-item :label="t('sys.account.nickname')">
                <a-input
                  allowClear
                  :placeholder="t('sys.account.nickname')"
                  v-model:value="formState.nickname"
                />
              </a-form-item>
            </a-col>

            <a-col :xs="24" :sm="6">
              <a-space>
                <a-button @click="Reactinquire" :icon="h(SearchOutlined)" type="primary">
                  {{ t('sys.form.placeholder.inquire') }}
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-tabs @change="activeKeyChange" v-model:activeKey="activeKey">
        <a-tab-pane key="1" :tab="t('sys.markerAccount.approval.approvalRecords')" />
        <a-tab-pane key="2" :tab="t('sys.markerAccount.markerRecord.markerRecords')" />
        <a-tab-pane key="4" :tab="t('sys.markerAccount.markerRecord.querySettlementRecordList')" />
      </a-tabs>

      <!-- 审批记录表格 -->
      <a-table
        v-if="activeKey == '1'"
        @change="handleApprovalTableChange"
        :pagination="approvalPagination"
        :loading="approvalLoading"
        bordered
        :scroll="{ x: 2000, y: 800 }"
        rowKey="id"
        :columns="approvalColumns"
        :dataSource="approvalDataSource"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'checkedStatus'">
            <a-tag v-if="record.checkedStatus == 1" color="blue"> 待审批 </a-tag>
            <a-tag v-if="record.checkedStatus == 2" color="green"> 已通过 </a-tag>
            <a-tag v-if="record.checkedStatus == 3" color="red"> 已拒绝 </a-tag>
          </template>
          <template v-if="column.dataIndex === 'refusalReasonnul'">
            <span>{{ record.markingRecordCount }}</span
            >/ <span>{{ record.markedNumber }}</span
            >/ <span style="color: green">{{ record.passMarkedNumber }}</span
            >/
            <span style="color: blue">{{ record.settlementNumber }}</span>
          </template>

          <template v-if="column.dataIndex === 'operation'">
            <a-space>
              <a-button
                v-if="record.checkedStatus == 2"
                @click="handleSettlement(record)"
                type="link"
              >
                {{ t('sys.markerAccount.settlement.settlement') }}
              </a-button>
              <!-- <a-popconfirm
                @confirm="deleteAccount(record)"
                :title="t('sys.configuration.IsDelete')"
                :ok-text="t('sys.configuration.comfig')"
                :cancel-text="t('sys.configuration.cancel')"
              >
                <a-button danger type="link"> {{ t('sys.configuration.delete') }}</a-button>
              </a-popconfirm> -->
              <a-button v-if="record.checkedStatus == 1" @click="approve(record, 2)" type="link">
                通过
              </a-button>
              <a-button v-if="record.checkedStatus == 1" @click="approve(record, 3)" type="link">
                拒绝
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 打标记录表格 -->
      <a-table
        v-if="activeKey == '2'"
        @change="handleMarkerRecordTableChange"
        :pagination="markerRecordPagination"
        :loading="markerRecordLoading"
        bordered
        :scroll="{ x: 2000, y: 800 }"
        rowKey="id"
        :columns="markerRecordColumns"
        :dataSource="markerRecordDataSource"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'targetName'">
            <div style="display: flex; flex-direction: column">
              <div class="flex">
                <div>
                  <a-image :src="windowUrl(record.avatorDetail)" :width="aivatWidthvalue + 'px'" />
                  <div class="text-center mt-2">
                    {{ record.targetName }}
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-if="column.dataIndex === 'customerAuditStatus'">
            <a-tag v-if="record.customerAuditStatus == 4" color="blue">
              {{ t('sys.userlist.preset.4') }}
            </a-tag>
            <a-tag
              v-if="record.customerAuditStatus != 0 && record.customerAuditStatus != 4"
              color="red"
            >
              <!-- {{ item.commentName }} -->
              {{
                presetComments[
                  presetComments.findIndex((item) => item.id == record.customerAuditStatus)
                ].commentName
              }}
            </a-tag>
            <a-tag v-if="record.customerAuditStatus == 0" color="orange">
              {{ t('sys.userlist.MarkingType.3') }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="record.status == 0" color="blue"> 待审核 </a-tag>
            <a-tag v-if="record.status == 1" color="green"> 未通过 </a-tag>
          </template>
        </template>
      </a-table>

      <!-- 结算记录表格 -->
      <a-table
        v-if="activeKey == '4'"
        @change="handleSettlementTableChange"
        :pagination="settlementPagination"
        :loading="settlementLoading"
        bordered
        :scroll="{ x: 2000, y: 800 }"
        rowKey="id"
        :columns="settlementColumns"
        :dataSource="settlementDataSource"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'settleFlag'">
            <a-tag v-if="record.settleFlag == 1" color="blue"> 未结算 </a-tag>
            <a-tag v-if="record.settleFlag == 2" color="green"> 已结算 </a-tag>
            <a-tag v-if="record.settleFlag == 3" color="orange"> 结算中 </a-tag>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-button
              v-if="record.settleFlag != 2"
              type="primary"
              size="small"
              @click="handleConfirmSettlement(record)"
            >
              确认结算
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 账号编辑抽屉 -->
    <a-drawer
      v-model:open="DrawerDetalsShow"
      class="custom-class"
      root-class-name="root-class-name"
      :title="addformState.id ? '编辑账号' : '新增账号'"
      placement="right"
    >
      <a-form :label-col="{ span: 6 }" :model="addformState">
        <a-form-item :label="t('sys.login.userName')">
          <a-input
            allowClear
            :placeholder="t('sys.configuration.pleaseenter') + t('sys.login.userName')"
            v-model:value="addformState.username"
            :disabled="!!addformState.id"
          />
        </a-form-item>
        <a-form-item :label="t('sys.account.nickname')">
          <a-input
            allowClear
            :placeholder="t('sys.configuration.pleaseenter') + t('sys.account.nickname')"
            v-model:value="addformState.nickname"
          />
        </a-form-item>
        <a-form-item v-if="!addformState.id" :label="t('sys.account.columns.password')">
          <a-input-password
            allowClear
            :placeholder="t('sys.configuration.pleaseenter') + t('sys.account.columns.password')"
            v-model:value="addformState.password"
          />
        </a-form-item>
        <a-form-item :label="t('sys.account.phone')">
          <a-input
            allowClear
            :placeholder="t('sys.configuration.pleaseenter') + t('sys.account.phone')"
            v-model:value="addformState.phone"
          />
        </a-form-item>
        <a-form-item :label="t('sys.account.email')">
          <a-input
            allowClear
            :placeholder="t('sys.configuration.pleaseenter') + t('sys.account.email')"
            v-model:value="addformState.email"
          />
        </a-form-item>
        <a-form-item :label="t('sys.account.columns.status')">
          <a-select
            :placeholder="t('sys.form.placeholder.status')"
            v-model:value="addformState.status"
          >
            <a-select-option :value="0">{{ t('sys.configuration.blockUp') }}</a-select-option>
            <a-select-option :value="1">{{ t('sys.configuration.startUsing') }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <a-divider />
      <div style="display: flex; justify-content: flex-end">
        <a-button @click="DrawerDetalsShow = false" style="margin-right: 8px">
          {{ t('sys.configuration.cancel') }}
        </a-button>
        <a-button @click="saveAccount" type="primary" size="small">
          {{ t('sys.configuration.comfig') }}
        </a-button>
      </div>
    </a-drawer>

    <!-- 结算模态框 -->
    <a-modal
      width="40%"
      v-model:open="settlementModalShow"
      :title="t('sys.markerAccount.settlement.settlement')"
      @ok="handleSettlementSubmit"
      @cancel="settlementModalShow = false"
    >
      <a-form :label-col="{ span: 6 }" :model="settlementForm">
        <a-form-item :label="t('sys.markerAccount.settlement.markerUser')">
          <a-input v-model:value="settlementForm.userName" disabled />
        </a-form-item>
        <a-form-item :label="t('sys.markerAccount.settlement.amount')">
          <a-input-number
            v-model:value="settlementForm.settlementAmount"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item :label="t('sys.device.columns.remck')">
          <a-textarea v-model:value="settlementForm.remark" rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 记录模态框（整合打标记录和结算记录） -->
    <a-modal
      width="80%"
      v-model:open="recordsModalShow"
      :title="`${currentViewAccount.nickname || ''} 的记录`"
      @cancel="recordsModalShow = false"
      footer=""
    >
      <a-tabs v-model:activeKey="recordsModalActiveKey" @change="handleRecordsModalTabChange">
        <a-tab-pane key="marker" :tab="t('sys.markerAccount.markerRecord.markerRecordList')">
          <a-table
            @change="handleMarkerRecordModalTableChange"
            :pagination="markerRecordModalPagination"
            :loading="markerRecordModalLoading"
            bordered
            :scroll="{ x: 2000, y: 600 }"
            rowKey="id"
            :columns="markerRecordColumns"
            :dataSource="markerRecordModalDataSource"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag v-if="record.status == 0" color="blue">
                  {{ t('sys.markerAccount.markerRecord.pending') }}
                </a-tag>
                <a-tag v-if="record.status == 1" color="green">
                  {{ t('sys.markerAccount.markerRecord.approved') }}
                </a-tag>
                <a-tag v-if="record.status == 2" color="red">
                  {{ t('sys.markerAccount.markerRecord.rejected') }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="settlement" :tab="t('sys.markerAccount.settlement.settlementRecordList')">
          <a-table
            @change="handleSettlementRecordModalTableChange"
            :pagination="settlementRecordModalPagination"
            :loading="settlementRecordModalLoading"
            bordered
            :scroll="{ x: 2000, y: 600 }"
            rowKey="id"
            :columns="settlementColumns"
            :dataSource="settlementRecordModalDataSource"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag v-if="record.status == 0" color="blue">
                  {{ t('sys.markerAccount.settlement.unsettled') }}
                </a-tag>
                <a-tag v-if="record.status == 1" color="green">
                  {{ t('sys.markerAccount.settlement.settled') }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-modal>

    <!-- 拒绝原因模态框 -->
    <Modal
      v-model:visible="rejectReasonModalVisible"
      title="填写拒绝原因"
      ok-text="确认拒绝"
      cancel-text="取消"
      @ok="confirmReject"
      @cancel="cancelReject"
    >
      <AntInput.TextArea
        v-model:value="rejectReason"
        placeholder="请输入拒绝原因"
        rows="4"
        allowClear
      />
    </Modal>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { onMounted, ref, h } from 'vue';
  import { message, Modal, Input as AntInput } from 'ant-design-vue';
  import { SearchOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import {
    columns,
    approvalColumns,
    markerRecordColumns,
    settlementColumns,
  } from './markerAccount.data';
  // 导入审批相关API
  import { commentlist } from '@/api/demo/device';
  import {
    getApprovalListAPI,
    doApprovalAPI,
    queryMarkingRecordListAPI,
    settlementHandle,
    querySettlementRecordList,
    finishSettlementHandle,
  } from '/@/api/demo/approval';

  const presetComments = ref([]);
  const { t } = useI18n();
  const initComment = () => {
    commentlist().then((res) => {
      presetComments.value = res.data;
    });
  };
  const windowUrl = (it) => {
    const isDomainAccess =
      !window.location.hostname.includes('192.168') &&
      !window.location.hostname.includes('127.0.0.1') &&
      !window.location.hostname.includes('localhost');
    if (isDomainAccess && it.includes('192.168')) {
      const path = it.split(':9000')[1];
      return window.location.protocol + '//' + window.location.hostname + path;
    } else if (isDomainAccess && it.includes('113.46.192.236')) {
      const path = it.split(':9000')[1];
      return window.location.protocol + '//' + 'mv.bckj.site' + path;
    } else {
      return it;
    }
  };
  // 表单状态
  const formState = ref({});
  const addformState = ref({});
  const settlementForm = ref({});

  // 加载状态
  const loading = ref(false);
  const approvalLoading = ref(false);
  const markerRecordLoading = ref(false);
  const settlementLoading = ref(false);

  // 数据源
  const dataSource = ref([]);
  const approvalDataSource = ref([]);
  const markerRecordDataSource = ref([]);
  const settlementDataSource = ref([]);

  // 分页信息
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  const approvalPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  const markerRecordPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  const settlementPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  // 抽屉和模态框显示状态
  const DrawerDetalsShow = ref(false);
  const settlementModalShow = ref(false);
  const recordsModalShow = ref(false);
  const recordsModalActiveKey = ref('marker');

  // 拒绝原因模态框
  const rejectReasonModalVisible = ref(false);
  const rejectReason = ref('');
  const currentApprovalRecord = ref(null);
  const currentApprovalStatus = ref(0);

  // 当前查看的账号信息
  const currentViewAccount = ref({});

  // 打标记录模态框分页信息
  const markerRecordModalPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  // 结算记录模态框分页信息
  const settlementRecordModalPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  // 打标记录模态框加载状态
  const markerRecordModalLoading = ref(false);
  const settlementRecordModalLoading = ref(false);

  // 打标记录模态框数据源
  const markerRecordModalDataSource = ref([]);
  const settlementRecordModalDataSource = ref([]);

  // 当前激活的标签页
  const activeKey = ref('1');

  // 模拟API调用
  const getMarkerAccountList = async (params) => {
    // 实际项目中替换为真实API调用
    return {
      code: 200,
      data: {
        records: [
          {
            id: '1',
            username: 'marker1',
            nickname: '打标员1',
            email: 'marker1@example.com',
            phone: '13800138001',
            status: 1,
            createTime: '2023-01-01 10:00:00',
          },
          {
            id: '2',
            username: 'marker2',
            nickname: '打标员2',
            email: 'marker2@example.com',
            phone: '13800138002',
            status: 1,
            createTime: '2023-01-02 10:00:00',
          },
        ],
        total: 2,
      },
    };
  };

  const getMarkerRecordList = async (params) => {
    // 实际项目中替换为真实API调用
    return {
      code: 200,
      data: {
        records: [
          {
            id: '1',
            taskId: 'task001',
            markerUser: 'marker1',
            markerTime: '2023-01-01 10:00:00',
            markerContent: '标记为重要',
            status: 1,
            remark: '',
          },
        ],
        total: 1,
      },
    };
  };

  const getSettlementList = async (params) => {
    // 实际项目中替换为真实API调用
    return {
      code: 200,
      data: {
        records: [
          {
            id: '1',
            markerUser: 'marker1',
            amount: 1000.0,
            settlementTime: '2023-01-01 10:00:00',
            status: 1,
            settlementUser: 'admin',
            remark: '1月份结算',
          },
        ],
        total: 1,
      },
    };
  };

  const saveMarkerAccount = async (params) => {
    // 实际项目中替换为真实API调用
    return { code: 200 };
  };

  const updateMarkerAccount = async (params) => {
    // 实际项目中替换为真实API调用
    return { code: 200 };
  };

  const deleteMarkerAccount = async (id) => {
    // 实际项目中替换为真实API调用
    return { code: 200 };
  };

  const toggleMarkerAccountStatus = async (id, status) => {
    // 实际项目中替换为真实API调用
    return { code: 200 };
  };

  // 审批操作函数
  const doApproval = async (id, status, remark) => {
    // 调用真实API
    return doApprovalAPI({
      id,
      checkedStatus: status === 1 ? 2 : 3, // 转换为后端需要的状态码：1未审批 2审批通过 3审批拒绝
      refusalReason: status === 2 ? remark : '', // 拒绝时需要拒绝原因
      remark,
    });
  };

  const doSettlement = async (params) => {
    // 实际项目中替换为真实API调用
    return { code: 200 };
  };

  // 初始化账号列表
  const init = () => {
    loading.value = true;
    getMarkerAccountList({
      size: pagination.value.pageSize,
      current: pagination.value.current,
      ...formState.value,
    }).then((res) => {
      if (res.code == 200) {
        dataSource.value = res.data.records;
        pagination.value.total = res.data.total;
      }
      loading.value = false;
    });
  };

  // 初始化审批记录
  const initApprovalList = () => {
    approvalLoading.value = true;
    // 调用真实API接口
    getApprovalListAPI({
      page: approvalPagination.value.current,
      pageSize: approvalPagination.value.pageSize,
      userName: formState.value.nickname,
    })
      .then((res) => {
        approvalDataSource.value = res.items || [];
        approvalPagination.value.total = res.total || 0;
        approvalLoading.value = false;
      })
      .catch(() => {
        approvalLoading.value = false;
      });
  };

  // 初始化打标记录
  const initMarkerRecordList = () => {
    markerRecordLoading.value = true;
    queryMarkingRecordListAPI({
      size: markerRecordPagination.value.pageSize,
      current: markerRecordPagination.value.current,
      userName: formState.value.nickname,
    }).then((res) => {
      if (res.code == 200) {
        markerRecordDataSource.value = res.data.records;
        markerRecordPagination.value.total = res.data.total;
      }
      markerRecordLoading.value = false;
    });
  };

  // 初始化结算记录
  const initSettlementList = () => {
    settlementLoading.value = true;
    querySettlementRecordList({
      size: settlementPagination.value.pageSize,
      current: settlementPagination.value.current,
      userName: formState.value.nickname,
    }).then((res) => {
      settlementDataSource.value = res.items;
      settlementPagination.value.total = res.total;
      settlementLoading.value = false;
    });
  };

  // 搜索
  const Reactinquire = () => {
    if (activeKey.value == '1') {
      approvalPagination.value.current = 1;
      initApprovalList();
    } else if (activeKey.value == '2') {
      markerRecordPagination.value.current = 1;
      initMarkerRecordList();
    } else if (activeKey.value == '4') {
      settlementPagination.value.current = 1;
      initSettlementList();
    }
  };

  // 新增账号
  const AddAccount = () => {
    addformState.value = { status: 1 };
    DrawerDetalsShow.value = true;
  };

  // 编辑账号
  const drawerEditBoxClick = (record) => {
    addformState.value = { ...record };
    DrawerDetalsShow.value = true;
  };

  // 保存账号
  const saveAccount = () => {
    if (addformState.value.id) {
      updateMarkerAccount(addformState.value).then((res) => {
        if (res.code == 200) {
          message.success(t('sys.api.operationSuccess'));
          DrawerDetalsShow.value = false;
          init();
        }
      });
    } else {
      saveMarkerAccount(addformState.value).then((res) => {
        if (res.code == 200) {
          message.success(t('sys.api.operationSuccess'));
          DrawerDetalsShow.value = false;
          init();
        }
      });
    }
  };

  // 打开结算模态框
  const handleSettlement = (record) => {
    settlementForm.value = {
      userId: record.userId,
      userName: record.userName,
      settlementAmount: 0,
      remark: '',
    };
    settlementModalShow.value = true;
  };

  // 提交结算
  const handleSettlementSubmit = () => {
    settlementHandle(settlementForm.value).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.markerAccount.settlement.settlementSuccess'));
        settlementModalShow.value = false;
        if (activeKey.value == '4') {
          initSettlementList();
        }
      }
    });
  };

  // 初始化打标记录模态框数据
  const initMarkerRecordModalList = () => {
    markerRecordModalLoading.value = true;
    getMarkerRecordList({
      size: markerRecordModalPagination.value.pageSize,
      current: markerRecordModalPagination.value.current,
      markerUser: currentViewAccount.value.username,
    }).then((res) => {
      if (res.code == 200) {
        markerRecordModalDataSource.value = res.data.records;
        markerRecordModalPagination.value.total = res.data.total;
      }
      markerRecordModalLoading.value = false;
    });
  };

  // 初始化结算记录模态框数据
  const initSettlementRecordModalList = () => {
    settlementRecordModalLoading.value = true;
    getSettlementList({
      size: settlementRecordModalPagination.value.pageSize,
      current: settlementRecordModalPagination.value.current,
      markerUser: currentViewAccount.value.username,
    }).then((res) => {
      if (res.code == 200) {
        settlementRecordModalDataSource.value = res.data.records;
        settlementRecordModalPagination.value.total = res.data.total;
      }
      settlementRecordModalLoading.value = false;
    });
  };

  // 查看记录（整合打标记录和结算记录）
  const viewRecords = (record) => {
    currentViewAccount.value = { ...record };
    recordsModalActiveKey.value = 'marker';
    // 初始化两个列表的数据
    markerRecordModalPagination.value.current = 1;
    settlementRecordModalPagination.value.current = 1;
    recordsModalShow.value = true;
    initMarkerRecordModalList();
    // 结算记录在切换到对应tab时再加载
  };

  // 处理记录模态框tab切换
  const handleRecordsModalTabChange = (key) => {
    recordsModalActiveKey.value = key;
    if (key === 'settlement') {
      initSettlementRecordModalList();
    }
  };

  // 审批操作
  const approve = (record, status) => {
    if (status === 3) {
      // 拒绝操作，显示模态框要求填写拒绝原因
      currentApprovalRecord.value = record;
      currentApprovalStatus.value = status;
      rejectReason.value = '';
      rejectReasonModalVisible.value = true;
    } else {
      // 通过操作，直接调用API
      doApprovalAPI({
        id: record.id,
        checkedStatus: status,
        userId: record.userId,
        refusalReason: '',
      })
        .then((res) => {
          if (res.code == 200) {
            message.success(t('sys.markerAccount.approval.approvalSuccess'));
            initApprovalList();
          } else {
            message.error(t('sys.markerAccount.approval.approvalFailed'));
          }
        })
        .catch(() => {
          message.error(t('sys.markerAccount.approval.approvalFailed'));
        });
    }
  };

  // 确认拒绝
  const confirmReject = () => {
    if (!rejectReason.value.trim()) {
      message.warning('请填写拒绝原因');
      return;
    }

    doApprovalAPI({
      id: currentApprovalRecord.value.id,
      checkedStatus: currentApprovalStatus.value,
      userId: currentApprovalRecord.value.userId,
      refusalReason: rejectReason.value,
    })
      .then((res) => {
        if (res.code == 200) {
          message.success(t('sys.markerAccount.approval.approvalSuccess'));
          rejectReasonModalVisible.value = false;
          initApprovalList();
        } else {
          message.error(t('sys.markerAccount.approval.approvalFailed'));
        }
      })
      .catch(() => {
        message.error(t('sys.markerAccount.approval.approvalFailed'));
      });
  };

  // 取消拒绝
  const cancelReject = () => {
    rejectReasonModalVisible.value = false;
    rejectReason.value = '';
  };

  // 标签页切换
  const activeKeyChange = (key) => {
    activeKey.value = key;
    if (key == '1') {
      initApprovalList();
    } else if (key == 2) {
      initMarkerRecordList();
    } else if (key == '4') {
      initSettlementList();
    }
  };

  // 表格分页变化
  const handleTableChange = (e) => {
    pagination.value = e;
    init();
  };

  const handleApprovalTableChange = (e) => {
    approvalPagination.value = e;
    initApprovalList();
  };

  const handleMarkerRecordTableChange = (e) => {
    markerRecordPagination.value = e;
    initMarkerRecordList();
  };

  const handleSettlementTableChange = (e) => {
    settlementPagination.value = e;
    initSettlementList();
  };

  // 模态框表格分页变化
  const handleMarkerRecordModalTableChange = (e) => {
    markerRecordModalPagination.value = e;
    initMarkerRecordModalList();
  };

  const handleSettlementRecordModalTableChange = (e) => {
    settlementRecordModalPagination.value = e;
    initSettlementRecordModalList();
  };

  // 处理确认结算
  const handleConfirmSettlement = async (record) => {
    try {
      // 显示确认对话框
      const confirmResult = await Modal.confirm({
        title: '确认结算',
        content: '确定要完成该结算记录吗？',
        okText: '确定',
        cancelText: '取消',
      });

      if (confirmResult) {
        // 调用完成结算接口
        const res = await finishSettlementHandle({
          id: record.id,
          settlementAmount: record.settlementAmount,
          remark: record.remark || '',
        });

        if (res && res.code === 200) {
          // 显示成功消息
          message.success('结算完成成功');

          // 刷新结算记录列表
          initSettlementRecordModalList();

          // 如果当前在结算列表页面，也刷新主页面的列表
          if (activeKey.value === '4') {
            initSettlementList();
          }
        } else {
          message.error('结算完成失败: ' + (res?.message || '未知错误'));
        }
      }
    } catch (error) {
      console.error('结算完成失败:', error);
      message.error('结算完成失败，请重试');
    }
  };

  // 页面加载时初始化
  onMounted(() => {
    initComment();
    initApprovalList();
  });
</script>

<style scoped lang="less"></style>
